package com.atguigu.springcloud.config;

import com.atguigu.springcloud.dto.BurnCancelTaskDto;
import com.atguigu.springcloud.dto.BurnTaskInfoDto;
import com.atguigu.springcloud.service.BurnService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.FADD;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.ObjectMessage;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 创建绑定交换机队列
 * @date 2021/10/15 16:07
 */
@ConditionalOnProperty(value = "burn.enable", havingValue = "true")
@Slf4j
public class RabbitmqConfig {

    @Autowired
    private BurnConfig burnConfig;

    @Autowired
    private CachingConnectionFactory connectionFactory;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BurnService burnService;


    @Bean("burnDownLoadExchange")
    public TopicExchange burnDownLoadExchange() {
        return new TopicExchange(burnConfig.getBurnDownloadExchange(), false, false);
    }

    @Bean("taskStatusQueue")
    public Queue remoteTrialTaskStatusQueue() {
        return new Queue(burnConfig.getTaskStatusQueue(), true);
    }


    @Bean
    public Binding taskStatusBinding(@Qualifier("burnDownLoadExchange") TopicExchange topicExchange,
                                     @Qualifier("taskStatusQueue") Queue taskStatusQueue) {
        return BindingBuilder.bind(taskStatusQueue).to(topicExchange).with(burnConfig.taskStatusRoutingKey);
    }


    //解决mq消息丢失问题
    @Bean
    public RabbitTemplate rabbitTemplate() {
        //若使用confirm-callback ，必须要配置publisherConfirms 为true
        connectionFactory.setPublisherConfirms(true);
        //若使用return-callback，必须要配置publisherReturns为true
        connectionFactory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //使用return-callback时必须设置mandatory为true，或者在配置中设置mandatory-expression的值为true
        rabbitTemplate.setMandatory(true);
        // 如果消息没有到exchange,则confirm回调,ack=false; 如果消息到达exchange,则confirm回调,ack=true
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    log.info("消息发送成功:correlationData({}),ack({}),cause({})", correlationData, ack, cause);
                } else {
                    log.info("消息发送失败:correlationData({}),ack({}),cause({})", correlationData, ack, cause);
                }
            }
        });

        //如果exchange到queue成功,则不回调return;如果exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}", exchange, routingKey, replyCode, replyText, message);
                byte[] body = message.getBody();
                try {
                    if (burnConfig.getTaskInfoRoutingkey().equals(routingKey)) {
                        BurnTaskInfoDto burnTaskInfoDto = objectMapper.readValue(body, BurnTaskInfoDto.class);
                        burnService.dealBurnTaskInfoDto(burnTaskInfoDto);
                    } else if (burnConfig.getDelTaskReqRoutingkey().equals(routingKey)) {
                        BurnCancelTaskDto burnCancelTaskDto = objectMapper.readValue(body, BurnCancelTaskDto.class);
                        burnService.dealBurnCancelTaskDto(burnCancelTaskDto);
                    }
                } catch (IOException e) {
                    log.error("处理消息丢失异常", e);
                }
            }
        });
        return rabbitTemplate;
    }


    /**
     * @param
     * @return
     * @description: 定义消费者对象
     */
    @Bean(name = "singleListenerContainer")
    public SimpleRabbitListenerContainerFactory listenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        //设置当前消费者数量
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(1);
        //设置每次从队列中拉取消息的数量
        factory.setPrefetchCount(1);
        factory.setTxSize(1);
        //设置当前的消费者确认为手动的，rabbit默认的是自动的
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }
}

